//
// Created by 32827 on 2024/7/24.
//
#include "yzl_none_ad9850.h"
YZF_RESULT yzl_ad9850_init(YZL_AD9850_DEF *ad9850){
    YLGPIO(ad9850->RESET)
    yzf_gpio_open_clock_();
    yzf_gpio_set_0_();
    yzf_gpio_set_Pull_Up_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_PP_();
    YLGPIO(ad9850->W_CLK)
    yzf_gpio_open_clock_();
    yzf_gpio_set_0_();
    yzf_gpio_set_Pull_Up_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_PP_();
    YLGPIO(ad9850->FQ_Update)
    yzf_gpio_open_clock_();
    yzf_gpio_set_0_();
    yzf_gpio_set_Pull_Up_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_PP_();
    YLGPIO(ad9850->DATA_OUT)
    yzf_gpio_open_clock_();
    yzf_gpio_set_0_();
    yzf_gpio_set_Pull_Up_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_PP_();

    ad9850->control = 0;
    ad9850->frequency = 0;
    YZF_MODIFY_REG(ad9850->control,YZL_AD9850_CTRL_CONTROL,0b00,YZL_AD9850_CTRL_CONTROL_POS);
    return YZF_OK;
}
YZF_RESULT yzl_ad9850_set_power_down(YZL_AD9850_DEF *ad9850,YZF_BOOL isDown){
    YZF_MODIFY_REG(ad9850->control,YZL_AD9850_CTRL_POWER_DOWN,isDown,YZL_AD9850_CTRL_POWER_DOWN_POS);
    return YZF_OK;
}
YZF_RESULT yzl_ad9850_set_phase(YZL_AD9850_DEF *ad9850,uint8_t phase){
    YZF_MODIFY_REG(ad9850->control,YZL_AD9850_CTRL_PHASE,phase,YZL_AD9850_CTRL_PHASE_POS);
    return YZF_OK;
}
double unitF=0.029103830456733704;
YZF_RESULT yzl_ad9850_set_frequency(YZL_AD9850_DEF *ad9850,uint32_t frequency){
    ad9850->frequency=(uint32_t)((double)frequency/(double)unitF);
    return YZF_OK;
}
YZF_RESULT yzl_ad9850_reset(YZL_AD9850_DEF *ad9850){
    YLGPIO(ad9850->RESET)
    yzf_gpio_set_1_();
    yzl_softport_delayUS(1);
    yzf_gpio_set_0_();
    return YZF_OK;
}
YZF_RESULT yzl_ad9850_fresh(YZL_AD9850_DEF *ad9850){
    YLGPIO(ad9850->FQ_Update)
    yzf_gpio_set_1_();
    yzl_softport_delayUS(1);
    yzf_gpio_set_0_();
    yzl_softport_delayUS(1);

    YLGPIO(ad9850->W_CLK)
    //w0-w31
    for(int i=0;i<32;i++){
        if(ad9850->frequency&(0b1<<i)){
            yzf_gpio_set_1(ad9850->DATA_OUT.port,ad9850->DATA_OUT.pin);
        }else{
            yzf_gpio_set_0(ad9850->DATA_OUT.port,ad9850->DATA_OUT.pin);
        }
        yzl_softport_delayUS(1);
        yzf_gpio_set_1_();
        yzl_softport_delayUS(1);
        yzf_gpio_set_0_();
        yzl_softport_delayUS(1);
    }
    //w32-w39
    for (int i = 0; i < 8; i++) {
        if(ad9850->control&(0b1<<i)){
            yzf_gpio_set_1(ad9850->DATA_OUT.port,ad9850->DATA_OUT.pin);
        }else{
            yzf_gpio_set_0(ad9850->DATA_OUT.port,ad9850->DATA_OUT.pin);
        }
        yzl_softport_delayUS(1);
        yzf_gpio_set_1_();
        yzl_softport_delayUS(1);
        yzf_gpio_set_0_();
        yzl_softport_delayUS(1);
    }

    YLGPIO(ad9850->FQ_Update)
    yzf_gpio_set_1_();
    yzl_softport_delayUS(1);
    yzf_gpio_set_0_();
    yzl_softport_delayUS(1);
    return YZF_OK;
}